package com.newland.starpos.partner.configuration;

import com.newland.starpos.partner.mvc.converter.CustomJackson2Converter;
import com.newland.starpos.partner.mvc.interceptor.AccessTokenInterceptor;
import com.newland.starpos.partner.mvc.interceptor.LoggerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.Charset;
import java.util.List;

/**
 * Created by liuNW on 2018/9/29.
 */
@EnableWebMvc
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Bean
    public HttpMessageConverter stringConverter(){
        return new StringHttpMessageConverter(Charset.defaultCharset());
    }

    @Bean
    public HttpMessageConverter jsonConverter(){
        return new CustomJackson2Converter();
    }

    @Bean
    public HandlerInterceptor loggerInterceptor(){
        return new LoggerInterceptor();
    }

    @Bean
    public HandlerInterceptor accessTokenInterceptor(){
        return new AccessTokenInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loggerInterceptor()).order(1)
                .addPathPatterns("/**");

        String[] excludeUrl = {"/user/phone/exist", "/user/registration", "/user/login"
                , "/user/password/reset", "/call/**", "/MerchantEntry/saveMerchant"
                , "/device/update/app/*", "/internal/**", "/authcode/**"};
        registry.addInterceptor(accessTokenInterceptor()).order(2)
                .addPathPatterns("/**")
                .excludePathPatterns(excludeUrl);
    }

    /**
     * Configure the {@link HttpMessageConverter}s to use for reading or writing
     * to the body of the request or response. If no converters are added, a
     * default list of converters is registered.
     * <p><strong>Note</strong> that adding converters to the list, turns off
     * default converter registration. To simply add a converter without impacting
     * default registration, consider using the method
     * {@link #extendMessageConverters(List)} instead.
     *
     * @param converters initially an empty list of converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(stringConverter());
        converters.add(jsonConverter());
    }


}
